package com.xzz.treeBST;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: hhz
 * @create: 2021-12-21 13:35
 * 95. 不同的二叉搜索树 II
 * 给你一个整数 n ，请你生成并返回所有由 n 个节点组成且节点值从 1 到 n 互不相同的不同 二叉搜索树 。可以按 任意顺序 返回答案。
 **/
public class GenerateTrees {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {
        }
        TreeNode(int val) {
            this.val = val;
        }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        List<TreeNode> treeNodes = generateTrees(3);
        System.out.println();
    }
    public static List<TreeNode> generateTrees(int n) {
        return build(1,n);
    }
    public static List<TreeNode> build(int start,int end) {
        List<TreeNode> res = new ArrayList<>();
        // base case
        if (start > end) {
            res.add(null);
            return res;
        }

        //以i为根节点 i左边作为左子树 i右边作为右子树
        for (int i = start;i<=end;i++){
            List<TreeNode> leftList = build(start, i - 1);
            List<TreeNode> rightList = build(i + 1, end);
            for (TreeNode leftNode : leftList) {
                for (TreeNode rightNode : rightList) {
                    TreeNode root = new TreeNode(i);
                    root.left = leftNode;
                    root.right = rightNode;
                    res.add(root);
                }
            }
        }
        return res;
    }
}
